<template>
  <div class="login-bg" :class="{ 'register-mode': isRegister }">
    <i class="iconfont icon-guanji" @click="onClose"
      style="z-index: 999999; position: fixed;top: 30px;right: 30px;color: #999;font-size: 40px;cursor: pointer;"></i>
    <div class="login-left">
      <div class="login-logo">
        <img src="../../assets/image/login_def_logo.png" alt="logo" class="logo-img" />
      </div>
      <div class="login-illustration"></div>
    </div>
    <div class="login-right">
      <div class="login-card">
        <transition name="slide-fade" mode="out-in">
          <div v-if="!isRegister && !showSecurity" key="login" class="form-content">
            <div class="login-title-row">
              <span class="login-title">{{ t('login.accountLogin') }}</span>
              <span class="login-divider">|</span>
              <span class="login-register" @click="isRegister = true">{{ t('login.register') }}</span>
            </div>
            <div class="login-form-row">
              <i class="iconfont icon-yonghu"></i>
              <input class="login-input" v-model="email" :placeholder="t('login.emailOrPhone')" />
              <div class="history-dropdown" @click="toggleHistoryDropdown">
                <el-icon :class="{ 'rotated': showHistoryDropdown }"><ArrowDown /></el-icon>
                <div v-if="showHistoryDropdown" class="history-menu">
                  <div v-if="loginHistory.length === 0" class="history-item empty">{{ t('login.noHistory') }}</div>
                  <div 
                    v-else
                    v-for="(item, index) in loginHistory" 
                    :key="index"
                    class="history-item"
                    @click.stop="selectHistoryItem(item)"
                  >
                    <div class="history-account">{{ item.account }}</div>
                    <i class="iconfont icon-shanchu history-delete" @click.stop="deleteHistoryItem(index)"></i>
                  </div>
                  <div v-if="loginHistory.length > 0" class="history-clear" @click.stop="clearAllHistory">
                    {{ t('login.clearAllHistory') }}
                  </div>
                </div>
              </div>
            </div>
            <div class="login-form-row">
              <i class="iconfont icon-mima"></i>
              <input class="login-input" v-model="password" type="password" :placeholder="t('login.password')" />
            </div>
            <div class="login-form-row login-form-row-bottom">
              <label class="login-remember">
                <input type="checkbox" v-model="remember" />
                <span>{{ t('login.rememberPassword') }}</span>
              </label>
              <span class="login-forgot" @click="onForgotPassword">{{ t('login.forgotPassword') }}</span>
            </div>
            <button class="login-btn" @click="onLogin">
              <span style="font-size: 22px;">→</span>
            </button>
          </div>
          <div v-else-if="isRegister && !showSecurity" key="register" class="form-content">
            <div class="login-title-row">
              <span class="login-title">{{ t('login.accountRegister') }}</span>
              <span class="login-divider">|</span>
              <span class="login-register" @click="isRegister = false">{{ t('login.login') }}</span>
            </div>
            <div class="login-form-row">
              <i class="iconfont icon-yonghu"></i>
              <input class="login-input" v-model="regUser" :placeholder="t('login.emailOrPhone')" />
            </div>
            <div class="login-form-row">
              <i class="iconfont icon-mima"></i>
              <input class="login-input" v-model="regPwd" type="password" :placeholder="t('login.enterPasswordPlaceholder')" />
            </div>
            <button class="login-btn" @click="onRegister">
              <span style="font-size: 22px;">→</span>
            </button>
          </div>
          <div v-else-if="showSecurity" key="security" class="form-content">
            <div class="login-title-row">
              <span class="login-title">{{ t('login.setSecurityQuestions') }}</span>
              <span class="login-divider">|</span>
              <span class="login-register login-back" @click="backToRegister">{{ t('login.previousStep') }}</span>
            </div>
            <div class="security-label">{{ t('login.cityQuestion') }}</div>
            <div class="login-form-row">
              <i class="iconfont icon-xiaoxi"></i>
              <input class="login-input" v-model="city" :placeholder="t('login.answerPlaceholder')" />
            </div>
            <div class="security-label">{{ t('login.jobQuestion') }}</div>
            <div class="login-form-row">
              <i class="iconfont icon-xiaoxi"></i>
              <input class="login-input" v-model="job" :placeholder="t('login.answerPlaceholder')" />
            </div>
            <button class="login-btn security-btn" @click="onSecuritySubmit">
              <span style="font-size: 28px;">✓</span>
            </button>
          </div>
        </transition>
      </div>
    </div>
    <Message ref="messageRef" />
    <Dialog ref="dialogRef">
      <div>
        <div style="color: #000;font-size: 22px;margin-top: 20px;">
          {{ t('login.confirmShutdown') }}
        </div>
        <div class="dialog-btn" style="margin-top: 70px;">
          <button class="dialog-confirm" @click="doExit">{{ t('login.confirm') }}</button>
          <button class="dialog-cancel" @click="dialogRef.close()">{{ t('login.cancel') }}</button>
        </div>
      </div>

    </Dialog>
    <ChangePassword ref="changePasswordRef" email />
  </div>
</template>

<script setup>
import { ArrowDown } from '@element-plus/icons-vue'
import { onMounted, onUnmounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import ChangePassword from '../../components/ChangePassword.vue'
import Dialog from '../../components/Dialog.vue'
import Message from '../../components/Message.vue'

// 翻译系统
const translationVersion = ref(0)
let t = (key, params) => {
  const keys = key.split('.')
  let current = translations.value
  for (const k of keys) {
    if (current && typeof current === 'object') {
      current = current[k]
    } else {
      return key
    }
  }
  if (typeof current === 'string' && params) {
    return current.replace(/\{(\w+)\}/g, (match, key) => params[key] || match)
  }
  return current || key
}

const translations = ref({})

async function initTranslations() {
  try {
    const currentLang = localStorage.getItem('language') || 'zh-CN'
    let langModule
    if (currentLang === 'en-US') {
      langModule = await import('../../i18n/locales/en-US')
    } else {
      langModule = await import('../../i18n/locales/zh-CN')
    }
    translations.value = langModule.default
    translationVersion.value++
  } catch (error) {
    console.error('Failed to load translations:', error)
  }
}

const email = ref('')
const password = ref('')
const remember = ref(true)
const isRegister = ref(false)
const regUser = ref('')
const regPwd = ref('')
const messageRef = ref(null)
const dialogRef = ref(null)
const router = useRouter()
const showSecurity = ref(false)
const city = ref('')
const job = ref('')
const showHistoryDropdown = ref(false)
const loginHistory = ref([])
const changePasswordRef = ref(null)
const hasAutoFilled = ref(false) // 添加标志跟踪是否已自动填充
const isPasswordChanged = ref(false) // 添加标志跟踪是否刚修改过密码

function onLogin() {
	// 校验邮箱/手机号不能为空
	if (!email.value || !email.value.trim()) {
		messageRef.value.show(t('login.enterEmailOrPhone'), 'error')
		return
	}
	
	// 校验密码不能为空
	if (!password.value || !password.value.trim()) {
		messageRef.value.show(t('login.enterPasswordValidation'), 'error')
		return
	}
	
	const trimmedInput = email.value.trim()
	
	// 邮箱格式正则表达式
	const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
	// 手机号格式正则表达式（支持11位数字，1开头）
	const phoneRegex = /^1[3-9]\d{9}$/
	
	// 检查是否为有效的邮箱或手机号
	const isValidEmail = emailRegex.test(trimmedInput)
	const isValidPhone = phoneRegex.test(trimmedInput)
	
	if (!isValidEmail && !isValidPhone) {
		messageRef.value.show(t('login.validEmailOrPhone'), 'error')
		return
	}
	
	window.request('/login', {
		method: 'POST',
		body: {
			username: trimmedInput,
			password: password.value.trim()
		}
  }).then(res => {
		console.log(res)
		window.messageRef.show(t('login.loginSuccess'))
		
		localStorage.setItem('token', res.token)
    localStorage.setItem('email', trimmedInput)
		
		if (remember.value) {
			localStorage.setItem('password', password.value.trim())
			// 只有勾选记住密码时才保存到历史记录
			saveToHistory(trimmedInput, password.value.trim())
		} else {
			localStorage.removeItem('password')
    }

    localStorage.setItem('resource', 0)
		
		// 清除首页数据缓存，确保重新登录后获取最新数据
		sessionStorage.removeItem('indexData')
		sessionStorage.removeItem('indexDataTimestamp')
		console.log('已清除首页数据缓存')
		
		// 触发登录成功事件，通知其他组件清除缓存
		window.dispatchEvent(new CustomEvent('loginSuccess'))
		
		// 登录成功后获取系统配置，设置语言
		getSystemConfig().then(() => {
			router.push('/member')
		}).catch(() => {
			// 即使获取配置失败也继续跳转
			router.push('/member')
		})
	}).catch(err => {
		console.log(err)
		// 登录失败时清空密码输入框，保留账号
		password.value = ''
		// 重置自动填充标志，允许用户重新输入
		hasAutoFilled.value = false
		// 重置修改密码标志，因为用户已经尝试登录
		isPasswordChanged.value = false
	})
}
const doExit = () => {
  // Electron 环境下关机
  if (window.electron && window.electron.ipcRenderer) {
    window.electron.ipcRenderer.invoke('shutdown-computer')
  } else {
    // 浏览器环境下的提示
    alert('此功能仅在桌面应用中可用')
  }
}
function onClose() {
  dialogRef.value.open()
}
function onRegister() {
  // 校验用户名不能为空
	if (!regUser.value || !regUser.value.trim()) {
		messageRef.value.show(t('login.enterEmailOrPhone'), 'error')
		return
	}
	
	const trimmedInput = regUser.value.trim()
	
	// 邮箱格式正则表达式
	const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
	// 手机号格式正则表达式（支持11位数字，1开头）
	const phoneRegex = /^1[3-9]\d{9}$/
	
	// 检查是否为有效的邮箱或手机号
	const isValidEmail = emailRegex.test(trimmedInput)
	const isValidPhone = phoneRegex.test(trimmedInput)
	
	if (!isValidEmail && !isValidPhone) {
		messageRef.value.show(t('login.validEmailOrPhone'), 'error')
		return
	}
	
	// 校验密码不能为空
	if (!regPwd.value || !regPwd.value.trim()) {
		messageRef.value.show(t('login.enterPasswordValidation'), 'error')
		return
	}
	
	// 校验密码长度
	if (regPwd.value.trim().length < 5 || regPwd.value.trim().length > 20) {
		messageRef.value.show(t('login.passwordLength'), 'error')
		return
	}
	
	// 校验通过，显示安全问题设置页面
	showSecurity.value = true
}
function backToRegister() {
  showSecurity.value = false
}
function onSecuritySubmit() {
  // 校验城市不能为空
  if (!city.value || !city.value.trim()) {
    messageRef.value.show(t('login.enterCity'), 'error')
    return
  }

  // 校验职业不能为空
  if (!job.value || !job.value.trim()) {
    messageRef.value.show(t('login.enterJob'), 'error')
    return
  }

  // 校验城市长度
  if (city.value.trim().length < 2) {
    messageRef.value.show(t('login.cityMinLength'), 'error')
    return
  }

  // 校验职业长度
  if (job.value.trim().length < 2) {
    messageRef.value.show(t('login.jobMinLength'), 'error')
    return
  }

  

  // 校验安全问题并提交注册
  // localStorage.setItem('token', '123456')
  // router.push('/')

  window.request('/register', {
    method: 'POST',
    body: {
      firstAnswer: city.value.trim(),
      secondAnswer: job.value.trim(),
      username: regUser.value.trim(),
      password: regPwd.value.trim(),
      uuid: '123'
    }
  }).then(res => {
    console.log(res)
    window.messageRef.show(t('login.registerSuccess'))
    isRegister.value = false
    email.value = regUser.value.trim()
    password.value = regPwd.value.trim()
    onLogin()
  }).catch(err => {
    console.log(err)
  })

}
function toggleHistoryDropdown() {
  showHistoryDropdown.value = !showHistoryDropdown.value
}
function selectHistoryItem(item) {
  email.value = item.account
  password.value = item.password
  showHistoryDropdown.value = false
  // 重置自动填充标志，因为用户主动选择了历史记录
  hasAutoFilled.value = false
  // 重置修改密码标志，因为用户主动选择了历史记录
  isPasswordChanged.value = false
}
function deleteHistoryItem(index) {
  const deletedItem = loginHistory.value[index]
  
  // 如果删除的是当前记住的账号，清除localStorage
  if (deletedItem && localStorage.getItem('email') === deletedItem.account) {
    localStorage.removeItem('email')
    localStorage.removeItem('password')
    // 如果当前输入框显示的就是这个账号，也清空
    if (email.value === deletedItem.account) {
      email.value = ''
      password.value = ''
    }
  }
  
  loginHistory.value.splice(index, 1)
  saveHistoryToStorage()
}
function clearAllHistory() {
  // 清空所有历史记录时，也清除localStorage中的记住信息
  localStorage.removeItem('email')
  localStorage.removeItem('password')
  // 清空当前输入框
  email.value = ''
  password.value = ''
  // 重置自动填充标志
  hasAutoFilled.value = false
  // 重置修改密码标志
  isPasswordChanged.value = false
  
  loginHistory.value = []
  saveHistoryToStorage()
}

// 保存登录记录到历史
function saveToHistory(account, pwd) {
  // 检查是否已存在
  const existingIndex = loginHistory.value.findIndex(item => item.account === account)
  
  if (existingIndex > -1) {
    // 如果存在，更新密码并移到最前面
    loginHistory.value.splice(existingIndex, 1)
  }
  
  // 添加到最前面
  loginHistory.value.unshift({
    account: account,
    password: pwd
  })
  
  // 只保留最近5条记录
  if (loginHistory.value.length > 5) {
    loginHistory.value = loginHistory.value.slice(0, 5)
  }
  
  saveHistoryToStorage()
}

// 保存历史记录到localStorage
function saveHistoryToStorage() {
  try {
    localStorage.setItem('loginHistory', JSON.stringify(loginHistory.value))
  } catch (error) {
    console.warn('保存历史记录失败:', error)
  }
}

// 从localStorage加载历史记录
function loadHistoryFromStorage() {
  try {
    const stored = localStorage.getItem('loginHistory')
    if (stored) {
      loginHistory.value = JSON.parse(stored)
    }
  } catch (error) {
    console.warn('加载历史记录失败:', error)
    loginHistory.value = []
  }
}

// 点击外部关闭下拉菜单
function handleClickOutside(event) {
  const dropdown = event.target.closest('.history-dropdown')
  if (!dropdown) {
    showHistoryDropdown.value = false
  }
}

function onForgotPassword() {
  changePasswordRef.value?.open(email.value)
}

// 获取系统配置并设置语言
async function getSystemConfig() {
  try {
    const res = await window.request('/system/config/getConfig', {
      method: 'GET',
    })
    
    if (res && res.lang) {
      // 设置语言到 localStorage
      localStorage.setItem('language', res.lang)
      console.log('登录后设置语言:', res.lang)
      
      // 重新初始化翻译
      await initTranslations()
      
      // 触发语言变化事件，通知其他组件
      window.dispatchEvent(new CustomEvent('language-changed', { 
        detail: { language: res.lang } 
      }))
    }
  } catch (error) {
    console.warn('获取系统配置失败:', error)
    // 失败时使用默认语言或当前语言
  }
}

onMounted(async () => {
  // 初始化翻译
  await initTranslations()
  
  // 加载历史记录
  loadHistoryFromStorage()
  
  // 添加全局点击事件监听
  document.addEventListener('click', handleClickOutside)
  
  // 检查是否是从修改密码页面跳转过来的
  const isFromPasswordChange = sessionStorage.getItem('passwordChanged')
  if (isFromPasswordChange) {
    isPasswordChanged.value = true
    sessionStorage.removeItem('passwordChanged') // 清除标记
    
    // 修改密码后跳转时，只填充账号，不填充密码
    const savedEmail = localStorage.getItem('email')
    if (savedEmail) {
      email.value = savedEmail
    }
    return // 直接返回，不执行后续的自动填充逻辑
  }
  
  // 只在首次加载且不是修改密码后跳转时自动填充账号密码
  const savedEmail = localStorage.getItem('email')
  const savedPassword = localStorage.getItem('password')
  
  if (savedEmail && savedPassword && !hasAutoFilled.value && !isPasswordChanged.value) {
    email.value = savedEmail
    password.value = savedPassword
    hasAutoFilled.value = true // 标记已自动填充
  }
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.dialog-btn {
  display: flex;
  justify-content: center;
  gap: 24px;
  margin-top: 32px;
}

.dialog-confirm {
  min-width: 90px;
  background: var(--theme-secondary);
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 18px;
  padding: 8px 0;
  cursor: pointer;
  transition: background 0.2s;
}

.dialog-confirm:hover {
  background: var(--theme-secondary-hover);
}

.dialog-cancel {
  min-width: 90px;
  background: #f3f3f3;
  color: #888;
  border: none;
  border-radius: 8px;
  font-size: 18px;
  padding: 8px 0;
  cursor: pointer;
  transition: background 0.2s;
}

.dialog-cancel:hover {
  background: #e0e0e0;
}

.login-bg {
  width: 100vw;
  height: 100vh;
  display: flex;
  transition: all 0.6s cubic-bezier(.77, 0, .18, 1);
}

.login-left {
  width: 50vw;
  height: 100vh;
  background: linear-gradient(135deg, var(--theme-primary) 60%, var(--theme-secondary) 100%);
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: flex-start;
  transition: all 0.6s cubic-bezier(.77, 0, .18, 1);
}

.login-logo {
  display: flex;
  align-items: center;
  margin: 48px 0 0 48px;
  gap: 18px;
}

.logo-img {
  width: 300px;
}

.logo-title {
  color: #fff;
  font-size: 22px;
  font-weight: bold;
  line-height: 1.2;
}

.login-illustration {
  margin-top: 80px;
  margin-left: 48px;
  width: 420px;
  height: 340px;
  background: url('/login-illustration.png') no-repeat center center;
  background-size: contain;
  opacity: 0.7;
}

.login-right {
  width: 50vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  transition: all 0.6s cubic-bezier(.77, 0, .18, 1);
}

.login-bg.register-mode .login-left {
  transform: translateX(50vw);
}

.login-bg.register-mode .login-right {
  transform: translateX(-50vw);
}

.login-card {
  /* padding: 30px !important; */
  box-sizing: border-box;
  width: 420px;
  min-height: 420px;
  background: #fff;
  border-radius: 12px;
  /* box-shadow: 0 8px 32px rgba(30,94,146,0.10), 0 2px 8px rgba(0,0,0,0.10); */
  padding: 48px 38px 38px 38px;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  position: relative;
  overflow: hidden;
  transition: all 0.6s cubic-bezier(.77, 0, .18, 1);
}

.form-content {
  position: absolute;
  width: 100%;
  left: 0;
  top: 0;
}

.login-title-row {
  display: flex;
  align-items: center;
  margin-bottom: 38px;
  gap: 18px;
}

.login-title {
  font-size: 32px;
  color: #222;
  font-weight: bold;
}

.login-divider {
  color: #bbb;
  font-size: 22px;
  margin: 0 8px;
}

.login-register {
  color: #bbb;
  font-size: 20px;
  cursor: pointer;
}

.login-form-row {
  display: flex;
  align-items: center;
  border-bottom: 1.5px solid #e0e6ed;
  margin-bottom: 28px;
  padding-bottom: 6px;
  font-size: 18px;
  position: relative;
}

.login-form-row-bottom {
  border-bottom: none;
  margin-bottom: 0;
  justify-content: space-between;
}

.login-input {
  border: none;
  outline: none;
  font-size: 15px;
  margin-top: 10px;
  flex: 1;
  background: transparent;
  color: #158ac0;
  padding: 6px 8px;
}

.iconfont {
  color: #158ac0;
  font-size: 22px;
  margin-right: 8px;
}

.login-remember {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #158ac0;
  font-size: 16px;
}

.login-forgot {
  color: #bbb;
  font-size: 16px;
  cursor: pointer;
}

.login-btn {
  width: 100%;
  margin-top: 38px;
  background: var(--theme-primary);
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 22px;
  padding: 12px 0;
  cursor: pointer;
  transition: background 0.2s;
}

.login-btn:hover {
  background: var(--theme-primary-hover);
}

.slide-fade-enter-active,
.slide-fade-leave-active {
  transition: all 0.5s cubic-bezier(.77, 0, .18, 1);
}

.slide-fade-enter-from {
  opacity: 0;
  transform: translateX(80px);
}

.slide-fade-leave-to {
  opacity: 0;
  transform: translateX(-80px);
}

.security-label {
  font-size: 18px;
  color: #222;
  margin: 28px 0 6px 0;
  font-weight: 500;
  text-align: left;
}

.security-btn {
  margin-top: 38px;
  font-size: 28px;
  background: var(--theme-primary);
  color: #fff;
}

.login-back {
  color: #bbb;
  font-size: 20px;
  cursor: pointer;
}

.history-dropdown {
  position: relative;
  display: flex;
  align-items: center;
  margin-left: 8px;
  cursor: pointer;
}

.history-dropdown .el-icon {
  font-size: 16px;
  color: #2176b8;
  transition: transform 0.2s;
}

.history-dropdown .el-icon:hover {
  color: #158ac0;
}

.history-dropdown .el-icon.rotated {
  transform: rotate(180deg);
}

.history-menu {
  position: absolute;
  top: calc(100% + 10px);
  right: 0;
  min-width: 200px;
  background: #fff;
  border: 1px solid #e0e6ed;
  border-radius: 8px;
  padding: 4px 0;
  max-height: 200px;
  overflow-y: auto;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.history-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 12px;
  cursor: pointer;
  transition: background 0.2s;
}

.history-item:hover:not(.empty) {
  background: #f0f8ff;
}

.history-item.empty {
  color: #999;
  cursor: default;
  text-align: center;
  font-size: 14px;
}

.history-account {
  font-size: 14px;
  color: #333;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.history-delete {
  color: #ccc;
  font-size: 14px;
  cursor: pointer;
  transition: color 0.2s;
  margin-left: 8px;
}

.history-delete:hover {
  color: #ff4757;
}

.history-clear {
  text-align: center;
  padding: 8px 12px;
  cursor: pointer;
  color: #158ac0;
  font-size: 14px;
  border-top: 1px solid #f0f0f0;
  margin-top: 4px;
  transition: background 0.2s;
}

.history-clear:hover {
  background: #f0f8ff;
}
</style>
